package com.cheers.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;
import cn.jpush.api.MessageResult;

import com.cheers.common.Constants;
import com.cheers.common.JPushUtil;
import com.cheers.dao.ProductDao;
import com.cheers.model.ExchangeProductLog;
import com.cheers.model.Product;
import com.cheers.mvo.ProductLog;
import com.cheers.service.IntegralService;
import com.cheers.service.ProductService;

public class ProductServiceImpl extends AbstractServiceImpl implements ProductService {

	@Resource
	private ProductDao productDao;
	@Resource
	private IntegralService integralService;
	
	
	@Override
	public void add(Product product) throws Exception {
		productDao.save(product);
	}


	
	@Override
	public int lastChance(String productId) throws Exception {
		Product product = productDao.get(Product.class, productId);
		if (product != null) {
			return product.getTotal()-product.getUses();
		}
		return 0;
	}
	
	@Override
	public void modStatus() throws Exception {
		//获取数据
		String sql = "select * from product_info where status=1 order by ctime asc";
		List<Product> productList = productDao.findListBySql(Product.class, sql, null);
		
		//修改状态
		if (productList!=null && !productList.isEmpty()) {
			for (Product product : productList) {
				product.setStatus(2);
				productDao.save(product);
			}
		}
	}

	@Override
	public String buy(String userId, String productId, int num)
			throws Exception {
		//获取商品
		Product product = productDao.get(Product.class, productId);
		if (product == null) {
			return null;
		}
		//是否已满
		if (product.getTotal() <= product.getUses()) {
			return Constants.PRODUCT_FULL_CODE;
		}
		
		//获取用户总积分
		Long total = integralService.getTotalPoint(userId);
		
		//剩余数量
		if (product.getTotal()-product.getUses() < num) {
			return Constants.PRODUCT_NOT_CODE;
		}
		
		//对比是否可以兑换商品
		int buyed = product.getBuyed();
		int needPoint = buyed*num;
		if (needPoint > total) {
			return Constants.POINT_TOTAL_CODE;
		}
		
		//兑换商品,减少总积分
		String data = integralService.addPoint(userId, Constants.DECREASE_BUY, -buyed);
		if (data == null) {
			return Constants.USER_CODE;
		}
		
		//兑换商品记录
		ExchangeProductLog exProductLog = new ExchangeProductLog();
		exProductLog.setUserId(userId);
		exProductLog.setProductId(productId);
		exProductLog.setPoint(buyed);
		exProductLog.setNum(num);
		exProductLog.setCtime(new Date());
		productDao.save(exProductLog);
		
		//计算使用数量
		product.setUses(product.getUses() + num);
		if (product.getTotal() <= product.getUses()) {
			product.setStatus(1);
			product.setOffTime(new Date());
		}
		productDao.save(product);
		
		//推送给兑换操作人
		push(userId);
		return Constants.OK;
	}
	
	private void push(String userId) {
		String jsonResult = JPushUtil.sendMessageWithAlias("8ab20e90449b215301449b34714b0001", "有人兑换商品", userId);
		MessageResult messageResult = (MessageResult) JSONObject.toBean(JSONObject.fromObject(jsonResult), MessageResult.class);
		if (messageResult.getErrcode() != 200) {
			logger.info("兑换商品推送失败:"+userId+". "+messageResult.getErrcode()+":"+messageResult.getErrmsg());
		}
	}

	@Override
	public List<Map<String, Object>> list(int pageIndex, int pageSize)
			throws Exception {
		List<Map<String, Object>> result = null;
		List<Product> list = productDao.list(pageIndex*pageSize, pageSize);
		if (list!=null && !list.isEmpty()) {
			result = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			for (Product p : list) {
				map = new HashMap<String, Object>();
				map.put("productId", p.getId());
				map.put("title", p.getTitle());
				map.put("price", String.format("%.2f", p.getPrice()));
				map.put("picture", getValue(p.getPicture()));
				map.put("describe", getValue(p.getDepict()));
				map.put("total", String.valueOf(p.getTotal()));
				map.put("last", String.valueOf(p.getTotal()-p.getUses()));
				map.put("buyed", String.valueOf(p.getBuyed()));
				map.put("ctime", sdf.format(p.getCtime()));
				result.add(map);
			}
		}
		return result;
	}
	
	public List<Map<String, Object>> exchangeList(String userId, int pageIndex, int pageSize) throws Exception {
		List<Map<String, Object>> result = null;
		List<ProductLog> list = productDao.exchangeList(userId, pageIndex*pageSize, pageSize);
		if (list!=null && !list.isEmpty()) {
			result = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			String status = null;
			for (ProductLog pl : list) {
				map = new HashMap<String, Object>();
				//商品
				map.put("productId", pl.getProductId());
				map.put("title", pl.getTitle());
				map.put("price", String.valueOf(pl.getPrice()));
				map.put("picture", getValue(pl.getPicture()));
				map.put("describe", getValue(pl.getDescribe()));
				//0,审核中  1,通过
				if ("0".equals(pl.getStatus())) {
					status = "审核中";
				} else if ("1".equals(pl.getStatus())) {
					status = "通过";
				}
				map.put("status", status);
				//记录
				map.put("point", String.valueOf(pl.getPoint()));
				map.put("number", String.valueOf(pl.getNumber()));
				map.put("ctime", pl.getCtime());
				result.add(map);
			}
		}
		return result;
	}
	
}
